import Cookies from 'js-cookie';

const getAllRules = function(data) {
    let res = [];
    function getRule(arrs) {
        arrs.forEach(item => {
            res.push(item.name);
            if(item._children && item._children.length > 0) {
                getRule(item._children);
            }
        })
    }
    getRule(data)
    return res;
}


const user = {
    state: {
        user: {}
    },
    mutations: {
        login(state, res) {
            const nodes = getAllRules(res.rules);
            this.commit('setUser', res);
            if(res.unsign) {
                Cookies.set('token', res.token, {
                    sameSite: 'None',
                    secure: true
                });
            }else{
                Cookies.set('token', res.token);
            }
            Cookies.set('nodes', nodes.join(','));
        },
        logout (state) {
            Cookies.remove('user');
            Cookies.remove('token');
            Cookies.remove('nodes');
        },
        setUser(state, user) {
            user.rules = [];
            state.user = user;
            Cookies.set('user', JSON.stringify(user));
        }
    }
};

export default user;
